﻿using System;
using System.Collections;
using System.Collections.Generic;

/**
 * 定时模块
 */
public class TimerSvc{

    class TaskPack{
        public int tid;
        public Action<int> cb;

        public TaskPack(int tid, Action<int> cb){
            this.tid = tid;
            this.cb = cb;
        }
    }
    
    private static TimerSvc instance = null;

    public static TimerSvc Instance{
        get{
            if (instance == null){
                instance = new TimerSvc();
            }

            return instance;
        }
    }

    private PETimer pt;
    private Queue<TaskPack> tpQue = new Queue<TaskPack>();
    private static readonly string tPQueLock = "tPQueLock";

    public void Init(){
        pt = new PETimer(100);
        tpQue.Clear();
        //设置日志
        pt.SetLog((string info) => {
            PECommon.Log(info);
        });
        pt.SetHandle((Action<int> action, int tid) => {
            if (action != null){
                lock (tPQueLock){
                    tpQue.Enqueue(new TaskPack(tid, action));
                }
            }
        });
        PECommon.Log("Init TimerSvc...");
    }

    public void Update(){
        while (tpQue.Count > 0){
            TaskPack tp = null;
            lock (tPQueLock){
                tp = tpQue.Dequeue();
            }

            if (tp != null){
                tp.cb(tp.tid);
            }
        }
    }
    
    public void AddTimerTask(Action<int> cb, double delay, PETimeUnit timeUnit = PETimeUnit.Millisecond, int count = 1){
        pt.AddTimeTask(cb, delay, timeUnit, count);
    }

    public long GetNowTime(){
        return (long)pt.GetMillisecondsTime();
    }
}